<!--
 * @Author: tansq
 * @Date: 2021-10-22 14:21:41
 * @LastEditTime: 2023-01-14 14:05:27
 * @LastEditors: tansq
 * @Description: luckShee导入模板
 * @FilePath: \hte-vue-dev\src\components\excelPaste\LuckSheetPaste.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->

<template>
  <j-modal
    :title="title"
    width="80vw"
    fullscreen
    :visible="excelVisible"
    @cancel="handleCancelExcel"
    @ok="handleOkExcel"
    :maskClosable="false"
    :confirm-loading="excelConfirmLoading"
    cancelText="关闭"
    :afterClose="afterClose"
  >
    <div style="min-height: 100%; position: relative">
      <div style="height: 50px">
        <slot name="downLoadBtn">
          <a-button icon="download" v-if="!downloadKey" @click="handleTemplate">下载模板</a-button>
          <commonAttachDownload style="display: inline-block;" v-else ref="downloader" :busKey="downloadKey"></commonAttachDownload>
        </slot>
        <a-button icon="download" @click="handleDownLoad">下载数据</a-button>
        <!-- <a-button icon="plus" @click="handleShowExcel" >粘贴导入</a-button> -->
        <span style="font-size: 12px; color: red; margin-left: 16px">(导入数据时单元格内容禁止按回车或者换行)</span>
      </div>

      <div
        id="luckysheet"
        class
        style="
          margin: 0px;
          padding: 0px;
          height: 90%;
          position: absolute;
          width: 100%;
          left: 0px;
          right: 0;
          top: 50px;
          bottom: 100px;
        "
      ></div>
    </div>
  </j-modal>
</template>

<script>
import { downloadFile, downloadFileLink } from '@/api/manage'
import { export_json_to_excel } from '@/utils/Export2Excel'
export default {
  name: 'LuckSheetPaste',

  components: {commonAttachDownload:()=> import('@/components/tools/commonAttachDownload'),},
  props: {
    //显示列
    title: {
      type: String,
      default: '批量导入',
    },
    columnsExcel: {
      type: Array,
      require: true,
    },

    //分页
    excelPagination: {
      type: Boolean,
      default: false,
      require: false,
    },
    //滚动
    excelScroll: {
      type: Object,
      default: () => {
        return { x: '100%', y: '100%' }
      },
      require: false,
    },

    //是否清空数据
    clearData: {
      type: Boolean,
      default: true,
      require: false,
    },
    downloadKey:{
        //新导入模板下载
        default: '',
        require:false
      },
  },
  data() {
    return {
      loading: false,
      excelConfirmLoading: false,
      excelVisible: false,
      selectedRowKeys: [],
      celldata: luckysheet.transToCellData([]),
      headers: [],
    }
  },
  created() {},
  methods: {
    init() {
      let luckysheetOptions = {
        container: 'luckysheet',
        title: this.title, //表 头名
        lang: 'zh', //中文
        showtoolbar: true, //是否显示工具栏
        showinfobar: false, //是否显示顶部信息栏
        showsheetbar: true, //是否显示底部sheet按钮,
        allowUpdate: true,
        column: this.columnsExcel.length,
        data: [{ celldata: luckysheet.transToCellData([this.headers]) }],
      }
      console.log(luckysheetOptions)
      if (!!window.luckysheet) {
        window.luckysheet.destroy()
        window.luckysheet.create(luckysheetOptions)
        window.luckysheet.setHorizontalFrozen(false)
      }
    },
    initByData(data) {
      let initData = [this.headers]
      if (data) {
        data.forEach((d) => {
          let temps = []
          this.columnsExcel.map((item) => {
            let value = d[item.dataIndex] ? d[item.dataIndex] : ''
            temps.push(value)
          })
          initData.push(temps)
        })
      }
      let luckysheetOptions = {
        container: 'luckysheet',
        title: this.title, //表 头名
        lang: 'zh', //中文
        showtoolbar: true, //是否显示工具栏
        showinfobar: false, //是否显示顶部信息栏
        showsheetbar: true, //是否显示底部sheet按钮,
        allowUpdate: true,
        column: this.columnsExcel.length,
        data: [{ celldata: luckysheet.transToCellData(initData) }],
      }
      console.log(luckysheetOptions)
      if (!!window.luckysheet) {
        window.luckysheet.destroy()
        window.luckysheet.create(luckysheetOptions)
        window.luckysheet.setHorizontalFrozen(false)
      }
    },
    getData() {
      let data = luckysheet.getAllSheets()
      this.$emit('close', data)
      console.log(data)
    },
    destroy() {
      if (!!window.luckysheet) {
        window.luckysheet.destroy()
      }
    },
    //关闭回调
    afterClose: function () {
      this.excelVisible = false
      this.destroy()
      this.excelConfirmLoading = false
    },

    showModalExcel: function () {
      this.excelConfirmLoading = false
      this.excelVisible = true
      this.$nextTick(() => {
        let headers = []
        this.columnsExcel.map((item) => {
          headers.push(item.title)
        })
        this.headers = headers
        this.init()
      })
    },
    handleErroMsg(mesg) {
      this.excelConfirmLoading = false
      this.$message.error(mesg || '导入数据出错！')
    },
    handleOkExcel: function () {
      let data = luckysheet.getAllSheets()
      if (!data) {
        this.$message.error('请导入数据！')
        return
      }
      const appendList = []
      if (data && data.length > 0) {
        for (const sheet of data) {
          // debugger;
          const rows = sheet.data
          for (const row of rows) {
            const appendData = []
            let index = 0
            let notEmptyRow = false
            for (const cell of row) {
              index++
              if (cell && cell.m) {
                notEmptyRow = true
                appendData.push(cell.m)
              } else {
                appendData.push('')
              }
            }
            if (notEmptyRow) {
              let tableRow = {}
              for (let j = 0; j < appendData.length; j++) {
                //第一列是序号
                let columnsIndex = j
                let cellData = appendData[j].replace(/\r/gi, '').replace(/\n/gi, '').replace(/\s+/gi, '')
                if (this.columnsExcel.length > columnsIndex) {
                  tableRow[this.columnsExcel[columnsIndex].dataIndex] = cellData
                }
              }
              appendList.push(tableRow)
            }
          }
        }
      }
      if (appendList.length < 2) {
        this.$message.error('请导入数据！')
        return
      }
      appendList.shift()
      this.excelConfirmLoading = true
      this.$emit('handleOkExcel', appendList, this)
    },
    handleCancelExcel: function () {
      // this.excelVisible = false;
      this.afterClose()
      this.$emit('handleCancelExcel')
    },

    handleTemplate() {
      const that = this

      const tHeader = []

      const data = [] //this.formatJson(filterVal, this.records);
      export_json_to_excel({
        header: this.headers,
        data,
        filename: `${that.title}导入模板`,
      })
    },
    handleDownLoad() {
      const that = this

      let data = luckysheet.getAllSheets()
      if (!data) {
        this.$message.error('请导入数据！')
        return
      }
      const appendList = []
      if (data && data.length > 0) {
        for (const sheet of data) {
          // debugger;
          const rows = sheet.data
          for (const row of rows) {
            const appendData = []
             let index = 0
            let notEmptyRow = false
            for (const cell of row) {
              index++
              if (cell && cell.m) {
                notEmptyRow = true
                appendData.push(cell.m)
              } else {
                appendData.push('')
              }
            }
            appendList.push(appendData)
          }
        }
      }
      if (appendList.length < 2) {
        this.$message.error('请导入数据！')
        return
      }
      appendList.shift()

      export_json_to_excel({
        header: this.headers,
        data: appendList,
        filename: `${that.title}导入`,
      })
    },
  },
  computed: {},
  filters: {},
  watch: {},
  mounted() {
    //this.init()
  },
  destroyed() {
    this.destroy()
  },
}
</script>


<style scoped>
.printHideCss {
  visibility: hidden !important;
}
.el-form-item >>> .el-form-item__error {
  color: #31a0e1;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: relative;
  top: 100%;
  left: 0;
}
.header {
  position: absolute;
  top: 0px;
  height: 50px;
  line-height: 50px;
  background: #ffffff;
  right: 0;
  left: 0;
}
.header button {
  margin: 0 10px;
}
</style>

